<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title></title>
    <meta name="description" content="">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="">
    <script>
        var websocket = null;

        // 主动连接
        function onConnect() {
            //判断当前浏览器是否支持WebSocket
            if ('WebSocket' in window) {
                if (websocket == null) {
                    //创建一个WebSocket连接，URL：127.0.0.1:8080/realTimeWebSocket/webSocket
                    document.getElementById("message").innerHTML = "欢迎来到我的主页222!";
                    websocket = new WebSocket("ws://localhost:8080/webSocket");
                    // websocket = new WebSocket("ws://121.196.38.160:8080/webSocket");
                } else {
                    alert('websocket is not null')
                }

            } else {
                alert('当前浏览器 不支持WebSocket')
            }
            //连接发生错误的回调方法
            websocket.onerror = function () {
                setMessageInnerHTML("连接发生错误");
            };

            //接收到消息的回调方法，此处添加处理接收消息方法，当前是将接收到的信息显示在网页上
            websocket.onmessage = function (event) {
                setMessageInnerHTML("接收成功" + event.data);
            }

            //连接关闭的回调方法
            websocket.onclose = function () {
                setMessageInnerHTML("连接关闭,如需登录请刷新页面。");
            }
        }

        // 主动发消息
        function onSend() {
            websocket.send("发送成功了啊啊啊啊啊啊啊啊啊啊啊"); //将消息发送到服务端
            setMessageInnerHTML("发送成功");
        }

        //关闭WebSocket连接
        function onClose() {
            websocket.close();
        }

        //监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常。
        window.onbeforeunload = function (event) {
            // closeWebSocket();
            //event.returnValue = "我在这写点东西...";
        }

        function setMessageInnerHTML(innerHTML) {
            document.getElementById('message').innerHTML += innerHTML + '<br/>';
        }


    </script>
</head>
<body>
<div>
    <button onclick="onConnect()">连接</button>
    <button onclick="onSend()">发送</button>
    <button onclick="onClose()">关闭</button>
    <div id='message'>123</div>
</div>
</body>
</html>